package spring.framework.beans.factory.support;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import spring.framework.beans.BeansException;
import spring.framework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @author pengzh
 * @class CglibInstantiationStrategy
 * @since 2021-09-23
 */
public class CglibInstantiationStrategy implements InstantiationStrategy {


    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor constructor, Object[] args) throws BeansException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if (constructor != null) {
            return enhancer.create(constructor.getParameterTypes(), args);
        }
        return enhancer.create();
    }
}
